<template>
  <div class="login-container">
    <el-card class="login-card">
      <div slot="header" class="login-header">
        <h2>AgriTech Dashboard</h2>
      </div>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="登录" name="login">
          <el-form :model="loginForm" :rules="loginRules" ref="loginForm">
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" prefix-icon="el-icon-user" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" prefix-icon="el-icon-lock" type="password" placeholder="密码"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleLogin" :loading="loading" style="width: 100%;">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="注册" name="register">
          <el-form :model="registerForm" :rules="registerRules" ref="registerForm">
            <el-form-item prop="username">
              <el-input v-model="registerForm.username" prefix-icon="el-icon-user" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="registerForm.password" prefix-icon="el-icon-lock" type="password" placeholder="密码"></el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input v-model="registerForm.confirmPassword" prefix-icon="el-icon-lock" type="password" placeholder="确认密码"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleRegister" :loading="loading" style="width: 100%;">注册</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.registerForm.confirmPassword !== '') {
          this.$refs.registerForm.validateField('confirmPassword');
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      activeTab: 'login',
      loading: false,
      loginForm: {
        username: '',
        password: ''
      },
      registerForm: {
        username: '',
        password: '',
        confirmPassword: ''
      },
      loginRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      registerRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }],
        confirmPassword: [{ validator: validatePass2, trigger: 'blur' }]
      }
    };
  },
  methods: {
    async handleLogin() {
      try {
        // 验证表单输入
        await this.$refs.loginForm.validate();
        this.loading = true;

        // 构造请求参数
        const params = new URLSearchParams();
        params.append('u_id', this.loginForm.username);
        params.append('u_password', this.loginForm.password);

        // 发送登录请求
        const response = await axios.post('http://localhost:8080/user/login', params);

        // 解析后端返回的 JSON 数据
        const data = response.data;

        if (data.message === '登录成功') {
          this.$message.success(data.message);

          // 存储用户信息到 localStorage
          localStorage.setItem('userId', data.u_id);
          localStorage.setItem('accessToken', data.access_token || '');
          localStorage.setItem('cloudToken', data.cloud_token || '');

          // 跳转到仪表盘页面
          this.$router.push('/dashboard');
        } else {
          // 登录失败处理
          this.$message.error(data.message || '登录失败');
        }
      } catch (error) {
        // 处理后端返回的错误
        if (error.response) {
          this.$message.error(error.response.data.message || '登录失败');
        } else if (error.request) {
          this.$message.error('网络错误，请稍后重试');
        } else {
          this.$message.error('登录失败');
        }
      } finally {
        this.loading = false;
      }
    },

    async handleRegister() {
      try {
        // 验证表单输入
        await this.$refs.registerForm.validate();
        this.loading = true;

        // 构造请求参数
        const params = new URLSearchParams();
        params.append('u_id', this.registerForm.username);
        params.append('u_password', this.registerForm.password);

        // 发送注册请求
        const response = await axios.post('http://localhost:8080/user/register', params);

        // 后端返回的是字符串，直接判断 response.data 的值
        const result = response.data;

        if (result === '注册成功') {
          this.$message.success(result);

          // 切换到登录选项卡
          this.activeTab = 'login';
        } else {
          // 注册失败处理
          this.$message.error(result || '注册失败');
        }
      } catch (error) {
        // 处理后端返回的错误
        if (error.response) {
          this.$message.error(error.response.data || '注册失败');
        } else if (error.request) {
          this.$message.error('网络错误，请稍后重试');
        } else {
          this.$message.error('注册失败');
        }
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.login-card {
  width: 400px;
}
.login-header {
  text-align: center;
  color: #409EFF;
}
</style>